/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Hmfs-tools resize defrag
 */

#ifndef RESIZE_DEFRAG_H
#define RESIZE_DEFRAG_H

#include <iostream>

#include "hmfs_fs.h"
#include "hmfs_log.h"
#include "resize_data.h"
#include "resize_utils.h"

namespace OHOS {
namespace Hmfs {
class ResizeOperator;
class ResizeDefrag {
public:
    ResizeDefrag(ResizeOperator *optPtr, std::shared_ptr<HmfsSuperBlockInfo> &superBlockInfo,
        std::shared_ptr<HmfsConfigData> &configData);
    ~ResizeDefrag() = default;
    bool WritePointerAtZoneStart(uint32_t zoneSegno);
    unsigned char *GetSegBitmap(SegmentEntry *sitEntry);
    unsigned char GetSegType(SegmentEntry *sitEntry);
    void SetSectionType(uint32_t sitNumber, int type);
    int32_t FindNextFreeBlock(uint64_t *to, int left, int wantType, bool newSec);
    unsigned short GetSegVblocks(SegmentEntry *sitEntry);
    void MoveOneCursegInfo(uint64_t from, int left, int i);
    void MoveCursegInfo(uint64_t from, int left);
    void ZeroJournalEntries();
    void WriteCursegInfo();
    void RewriteCurrentSitPage(uint32_t sitNumber, SitBlockData *sitBlk);
    void FlushSitEntries();
    void UpdateSumEntry(uint32_t blockAddr, SummaryEntry *sum);
    int32_t HmfsMigrateBlock(uint64_t from, uint64_t to);
    int32_t HmfsDefragment(uint64_t from, uint64_t len, uint64_t to, int left);

private:
    uint64_t CalculateEndBlockAddress();
    int32_t CheckFreeSegments();
    void ProcessNextBlock(uint64_t *to, int left, uint32_t sitNumber);
    int32_t CheckSegmentFull(SegmentEntry *sitEntry);
    int32_t ProcessEmptySegment(uint32_t sitNumber, int32_t wantType);
    bool CheckValidBlock(uint32_t offset, unsigned char *bitmap,
        unsigned char type, int32_t wantType, bool newSec);
    ResizeOperator *opt_ = nullptr;
    std::shared_ptr<HmfsSuperBlockInfo> superBlockInfo_ = nullptr;
    std::shared_ptr<HmfsConfigData> config_ = nullptr;
};

} // namespace Hmfs
} // namespace OHOS
#endif // RESIZE_DEFRAG_H
